package com.swang.security.service.biz.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.swang.security.dal.UserDao;
import com.swang.security.model.dto.UserDetailDto;
import com.swang.security.model.vo.UserDetailVo;
import com.swang.security.service.biz.UserService;

/**
 * @ClassName: UserServiceImpl
 * @Description: 用户接口服务实现
 * @author swang
 * @date 2017年4月17日 下午7:58:22
 */
@Service
public class UserServiceImpl implements UserService {
	
	//	/^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/
	private static final String emailRegex = "(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w{2,3}){1,3})";
	//	/^(\w)+(\&\w+)+$/
	//private static final String extendAuthRegex = "(\\w)+(\\&\\w+)+";
	private static final String extendAuthRegex = "(\\w)+(\\.\\w+)*(\\&(\\w)+(\\.\\w+)*)+";
	private static final String phoneRegex = "1[3-8][0-9]\\d{8}";
	
	@Autowired
	private UserDao userDao;

	@Transactional
	@Override
	public UserDetailVo findUserByUserName(String userName) {
		if(StringUtils.isBlank(userName) || userName.length()>64){
			return null;
		}
		if(userName.matches(emailRegex)){
			return userDao.findUserByEmail(userName);
		}
		if(userName.matches(extendAuthRegex)){
			return userDao.findUserByExtendAuth(userName);
		}
		if(!userName.matches(phoneRegex)){
			return userDao.findUserByUserName(userName);
		}
		// 剩下的是手机号格式，可能需要匹配phone_no，也有可能要匹配user_name
		Long phoneNo = Long.parseLong(userName);
		UserDetailVo userDetail = userDao.findUserByPhoneNo(phoneNo);
		if(userDetail!=null && userDetail.getUserId()!=null && userDetail.getUserId()>0){
			return userDetail;
		}
		userDetail = userDao.findUserByUserName(userName);
		if(userDetail!=null && userDetail.getUserId()!=null && userDetail.getUserId()>0){
			// 更新user_name中的手机号到phone_no字段中
			userDao.updateUserPhoneNo(new UserDetailDto(userName, phoneNo));
			return userDetail;
		}
		return userDetail;
	}
	
}
